package edu.luas.digitalmedia.dao;

import edu.luas.digitalmedia.pojo.User;

import java.sql.*;

public class UserDao {
    public int insert(User model) throws Exception {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1:从连接池中获取 connection 对象
            connection = DBHelper.getConnection();

            //2:创建执行语句对象 statement
            String sql = "insert into sec_c6_manage (username, password ) values(?,?) ";
            statement = connection.prepareStatement(sql);
            statement.setObject(1, model.getUsername());
            statement.setObject(2, model.getPassword());

            //3：执行 sql 语句，返回影响行数
            int count = statement.executeUpdate();

            //4:处理结果
            return count;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            //5：关闭资源
            DBHelper.close(statement, connection);
        }
    }
    public boolean authenticateUser(String username, String password) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1:从连接池中获取 connection 对象
            connection = DBHelper.getConnection();

            // 使用预编译语句来防止SQL注入攻击
            String sql = "SELECT * FROM sec_c6_manage WHERE username=? AND password=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet rs = statement.executeQuery();

            if (rs.next()) {
                // 用户验证通过
                return true;
            }

            rs.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}

